package io.xxx.xbutler.core.callback;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.xxx.xbutler.data.RoomContactMapper;
import io.xxx.xbutler.domain.Callback;
import io.xxx.xbutler.domain.RoomContact;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 新成员入群扫码地址回调
 * <p>
 * 当群内有新成员是通过扫机器人分享的群二维码入群时，机器人收到新成员入群回调的同时也会收到此回调，回调顺序不分先后；
 * 通过该接口将扫码入群的新成员扫描的二维码地址回调给商家
 * 商家收到此回调的前提：
 * 1、有新成员通过扫描机器人分享的二维码入群
 * 2、分享二维码的机器人关注群
 *
 * <pre>
 * {
 *     "nType": 4519,
 *     "vcMerchantNo": "",
 *     "vcRobotWxId": "",
 *     "vcRobotSerialNo": "",
 *     "vcSerialNo": "",
 *     "nResult": 1,
 *     "vcResult": "SUCCESS",
 *     "Data": {
 *         "vcChatRoomId": "",
 *         "vcChatRoomSerialNo": "",
 *         "vcChatRoomQrcode": "",
 *         "vcUserWxId": "",
 *         "vcUserWxSerialNo": "",
 *         "vcUserNickName": "",
 *         "vcRemark": "通过扫描你分享的二维码加入群聊"
 *     },
 *     "nTimeStamp": 1608563382879
 * }
 * </pre>
 */
@Slf4j
@Component
public class _4519Handler implements CallbackHandler {

    @Resource
    private RoomContactMapper roomContactMapper;

    @Override
    public String name() {
        return "新成员入群扫码地址回调";
    }

    @Override
    public boolean supports(int type) {
        return type == 4519;
    }

    @Override
    public void handle(Callback callback) {
        LocalDateTime now = LocalDateTime.now();
        JSONObject data = (JSONObject) callback.getData();

        String roomId = data.getString("vcRoomId");
        String contactId = data.getString("vcUserWxId");
        if (!isExists(roomId, contactId)) {
            RoomContact roomContact = new RoomContact()
                    .setRoomId(roomId)
                    .setRoomSerialNo(data.getString("vcRoomSerialNo"))
                    .setContactId(contactId)
                    .setContactSerialNo(data.getString("vcUserWxSerialNo"))
                    .setContactName(data.getString("vcUserNickName"))
                    .setJoinTime(callback.getTimestamp())
                    .setJoinRemark(data.getString("vcRemark"))
                    .setCreatedTime(now)
                    .setUpdatedTime(now);
            roomContactMapper.insert(roomContact);
        }
    }

    private boolean isExists(String roomId, String contactId) {
        LambdaQueryWrapper<RoomContact> wrapper = new LambdaQueryWrapper<RoomContact>()
                .eq(RoomContact::getRoomId, roomId)
                .eq(RoomContact::getContactId, contactId);
        return roomContactMapper.exists(wrapper);
    }
}
